<?php

namespace App\Http\Controllers\Weixin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\WxMenu;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class WxMenuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = WxMenu::get()->toTree();
        return $this->success('', ['data' => $list]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $attributes = $request->input();
        $pid = $request->input('pid');
        $node = null;
        if($pid) {
            $node = WxMenu::find($pid);
        }
        WxMenu::create($attributes, $node);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         $node = WxMenu::findOrFail($id);
         $node->update($request->input());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $node = WxMenu::findOrFail($id);
        if (!$node->delete()) {
            return $this->error('删除失败');
        }
    }
    
    public function updateMenu()
    {
        $app = app('wechat.official_account');
        $buttons = WxMenu::get()->toTree();
        $normalMenu = $this->toMenu($buttons)->all();
        return $app->menu->create($normalMenu);
    }
    
    //格式菜单
    protected function toMenu($data) {
        $result = collect($data)->map(function($item){
            $rs = collect($item)->filter(function ($value) {
                return $value;
            });
            if($rs->has('children')){
                $rs->put('sub_button', $this->toMenu($rs->get('children')));
                $rs->forget('children');
            }
            return $rs;
        });
        return $result;
    }
}
